﻿using System;
using System.Web.UI;
using Ninject;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using System.Web.UI.WebControls;
using Legazpi.Payroll.DataAccess.DataObjects;
using Legazpi.Payroll.DataAccess.DataObjects.Enums;
using Web.Codes;
using Web.Utils;

namespace Legazpi.Payroll.Web.Admin
{
    public partial class Clients : System.Web.UI.Page
    {
        [Inject]
        public IClientService _clientService { get; set; }

        [Inject]
        public IDetachmentService _detachmentService { get; set; }

        public bool IsSuccess { get; set; }
        public bool IsSuccessSector { get; set; }
        public bool FoundError { get; set; }
        public string NotifyText { get; set; }
        
        private int _clientId;
        public int CurrentClientId 
        {
            get
            {   
                return !string.IsNullOrEmpty(ClientId.Value) ? int.Parse(ClientId.Value) : 0;
            }            
        }
        private Client _currentClient;
        public Client CurrentClient
        {
            get
            {
                return _currentClient ?? _clientService.GetById(CurrentClientId);
            }
            set { _currentClient = value; }
        }

        #region Implementations
        void BindGrid()
        {
            repeater.DataSource = _clientService.GetAll();
            repeater.DataBind();
        }

        void Delete(int id)
        {
            _clientService.Delete(id);
            IsSuccess = _clientService.Save();
            FoundError = !IsSuccess;

            if (!IsSuccess)
            {
                NotifyText = "Cannot be deleted, found error or there is a dependency on this record.";
            }
            else
            {
                NotifyText = "Successfully Deleted.";
            }

            BindGrid();
        }

        void Edit(int id)
        {
            //var client = _clientService.GetById(id);
            CurrentClient = _clientService.GetById(id);
            ObjectToData(CurrentClient);

            BindGridDetachments();

            SubmitBtn.Text = "Update";
            SubmitSectorBtn.Enabled = true;
            SectorDropList.ToSectorSelectList(0,CurrentClientId);
        }
        void Update(int id)
        {
            var client = _clientService.GetById(id);
            if (client == null)
            {
                Add();
                return;
            }
            DataToObject(ref client);

            _clientService.Update(client);
            IsSuccess = _clientService.Save();
            NotifyText = "Successfully Updated Record.";
            ClearForm();
            BindGrid();
        }

        void Add()
        {
            var client = new Client();

            DataToObject(ref client);

            _clientService.Add(client);
            IsSuccess = _clientService.Save();
            NotifyText = "Successfully Added New Record.";
            BindGrid();
        }
        void DataToObject(ref Client obj)
        {
            double tempDbl;
            obj.Code = CodeTxt.Text;
            obj.FirmName = FirmNameTxt.Text;
            obj.ContactNo = ContactNoTxt.Text;
            obj.Address = AddressTxt.Text;

            obj.RegularOverTime = double.TryParse(RegOTtxt.Text, out tempDbl) ? tempDbl : 0;
            obj.SpecialOverTime = double.TryParse(SpclOTtxt.Text, out tempDbl) ? tempDbl : 0;
            obj.LegalHoliday = double.TryParse(Legaltxt.Text, out tempDbl) ? tempDbl : 0;
            obj.SpecialHoliday = double.TryParse(Spcltxt.Text, out tempDbl) ? tempDbl : 0;
            obj.NightDiff = double.TryParse(NightDiffTxt.Text, out tempDbl) ? tempDbl : 0;
        }
        void ObjectToData(Client obj)
        {
            ClientId.Value = obj.Id.ToString();
            CodeTxt.Text = obj.Code;
            FirmNameTxt.Text = obj.FirmName;
            ContactNoTxt.Text = obj.ContactNo;
            AddressTxt.Text = obj.Address;

            RegOTtxt.Text = obj.RegularOverTime.ToString();
            SpclOTtxt.Text = obj.SpecialOverTime.ToString();
            Legaltxt.Text = obj.LegalHoliday.ToString();
            Spcltxt.Text = obj.SpecialHoliday.ToString();
            NightDiffTxt.Text = obj.NightDiff.ToString();
        }
        void Save()
        {
            int Id;
            int.TryParse(ClientId.Value, out Id);
            if (Id == 0)
                Add();
            else
                Update(Id);
        }

        void ClearForm()
        {
            ClearControl(this.Page);
            ClientId.Value = "0";            
            SubmitBtn.Text = "Submit";
            SubmitSectorBtn.Enabled = false;
            repeaterSector.DataSource = null;
            repeaterSector.DataSourceID = null;
            repeaterSector.DataBind(); 
        }
        void ClearControl(Control ctrl)
        {
            foreach (Control _ctrl in ctrl.Controls)
            {
                if (_ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)_ctrl).Text = string.Empty;
                }
                else if (_ctrl.GetType() == typeof(DropDownList))
                {
                    ((DropDownList)_ctrl).SelectedIndex = 0;
                }
                ClearControl(_ctrl);
            }
        }
        #endregion

        #region ImplementSectors
        void BindGridDetachments()
        {
            repeaterSector.DataSource = _detachmentService.GetAllByClientId(CurrentClientId);
            repeaterSector.DataBind();
        }

        void DeleteSector(int id)
        {
            //_sectorService.Delete(id);
            //IsSuccessSector = _sectorService.Save();
            NotifyText = "Successfully Deleted.";

            BindGridDetachments();
        }

        void EditDetachment(int id)
        {
            var detachment = _detachmentService.GetById(id);
            PositionDropList.ClearSelection();
            SectorDropList.ClearSelection();

            ObjectToDataSector(detachment);

            SubmitSectorBtn.Text = "Update";
        }
        void UpdateDetachment(int id)
        {
            var detachment = _detachmentService.GetById(id);
            if (detachment == null)
            {
                AddDetachment();
                return;
            }
            DataToObjectSector(ref detachment);

            _detachmentService.Update(detachment);
            IsSuccessSector = _detachmentService.Save();
            NotifyText = "Successfully Updated Record.";
            ClearFormSelector();
            BindGridDetachments();
        }

        void AddDetachment()
        {
            var detachment = new Detachment();

            DataToObjectSector(ref detachment);

            _detachmentService.Add(detachment);
            IsSuccessSector = _detachmentService.Save();
            NotifyText = "Successfully Added New Record.";
            BindGridDetachments();
        }
        void DataToObjectSector(ref Detachment obj)
        {
            double tempDbl;            
            obj.WorkHours = double.TryParse(WorkHourTxt.Text, out tempDbl) ? tempDbl : 0;
            obj.RatePerDay = double.TryParse(RatePerDayTxt.Text, out tempDbl) ? tempDbl : 0;
            obj.RatePerHour = double.TryParse(RatePerHourTxt.Text, out tempDbl) ? tempDbl : 0;

            if (SectorDropList.SelectedIndex > 0)
                obj.SectorId = int.Parse(SectorDropList.SelectedValue);            

            if (PositionDropList.SelectedIndex > 0)
                obj.PositionId = int.Parse(PositionDropList.SelectedValue);            
        }
        void ObjectToDataSector(Detachment obj)
        {                        
            WorkHourTxt.Text = obj.WorkHours.ToString();
            RatePerDayTxt.Text = obj.RatePerDay.ToString();
            RatePerHourTxt.Text = obj.RatePerHour.ToString();

            var sector = SectorDropList.Items.FindByValue(obj.SectorId.ToString());
            if (sector != null)
                sector.Selected = true;

            var pos = PositionDropList.Items.FindByValue(obj.PositionId.ToString());
            if (pos != null)
                pos.Selected = true;

        }
        void SaveDetachment()
        {
            int Id;
            int.TryParse(DetachmentId.Value, out Id);
            if (Id == 0)
                AddDetachment();
            else
                UpdateDetachment(Id);
        }
        public string GetPositionCode(RepeaterItem item)
        {
            //var pos = ((Sector)item.DataItem).Position;
            //return pos != null ? pos.Code : string.Empty;
            return "";
        }
        void ClearFormSelector()
        {
            PositionDropList.ClearSelection();            
            SectorNameTxt.Text = string.Empty;
            WorkHourTxt.Text = string.Empty;
            RatePerDayTxt.Text = string.Empty;
            RatePerHourTxt.Text = string.Empty;
            PositionDropList.SelectedIndex = 0;
            SubmitSectorBtn.Text = "Submit";
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
                PositionDropList.ToPositionSelectList(0);
                //SectorDropList.ToSectorSelectList(0);                
            }
        }

        protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case Constants.Update_Command:
                        Edit(intTemp);
                        break;
                    case Constants.Delete_Command:
                        Delete(intTemp);
                        break;
                }
            }
        }

        protected void repeaterSector_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case Constants.Update_Command:
                        EditDetachment(intTemp);
                        break;
                    case Constants.Delete_Command:
                        DeleteSector(intTemp);
                        break;
                }
            }
        }

        protected void AddNewBtn_Click(object sender, EventArgs e)
        {
            Save();
            if (IsSuccess)
            {
                ClearForm();
                BindGrid();
            }
        }

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            ClearForm();            
            SubmitSectorBtn.Text = "Submit";           
        }

        protected void SubmitSectorBtn_Click(object sender, EventArgs e)
        {
            SaveDetachment();
            if (IsSuccessSector)
            {
                ClearFormSelector();
                BindGridDetachments();
            }
        }

        protected void AddSectorBtn_Click(object sender, EventArgs e)
        {
            var sector = new Sector
                {
                    Name = SectorNameTxt.Text,                                        
                };
            CurrentClient.Sectors.Add(sector);

            _clientService.Update(CurrentClient);
            _clientService.Save();

            SectorNameTxt.Text = string.Empty;
            SectorDropList.ToSectorSelectList(sector.Id,CurrentClientId);  
        }

        protected void repeaterSector_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var sectorNameLiteral = (Literal)e.Item.FindControl("SectorNameLiteral");
                var detachmentIdHidden = (HiddenField)e.Item.FindControl("DetachmentIdHidden");
                var positionCodeLiteral = (Literal)e.Item.FindControl("PositionCodeLiteral");                
                var workHourLiteral = (Literal)e.Item.FindControl("WorkHourLiteral");
                var rateDayLiteral = (Literal)e.Item.FindControl("RateDayLiteral");
                var rateHourLiteral = (Literal)e.Item.FindControl("RateHourLiteral");
                
                var detachItem = (Detachment)e.Item.DataItem;

                sectorNameLiteral.Text = detachItem.Sector.Name;
                detachmentIdHidden.Value = detachItem.Id.ToString();
                positionCodeLiteral.Text = detachItem.Position.Code;
                workHourLiteral.Text = detachItem.WorkHours.ToString("N");
                rateDayLiteral.Text = detachItem.RatePerDay.ToString("N");
                rateHourLiteral.Text = detachItem.RatePerHour.ToString("N");
            }
        }
    }
}